﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
/******
Assign       ,generate entity, total 10000 rows, time: 3
Emit         ,generate entity, total 10000 rows, time: 7
Expression   ,generate entity, total 10000 rows, time: 38
Reflection   ,generate entity, total 10000 rows, time: 39
Delegate     ,generate entity, total 10000 rows, time: 137
http://www.cnblogs.com/andyliu/archive/2012/03/17/2402865.html
 * ****/
namespace TEmit
{

    public delegate void SetString(string value);
    public class ToEntityByDelegate<T>
    {
        public List<T> GetEntity(DataTable dt)
        {
            List<T> lst = new List<T>();
            Type type = typeof(T);
            SetString setDelegateString;

            foreach (DataRow dr in dt.Rows)
            {
                T model = (T)Activator.CreateInstance(typeof(T));
                foreach (DataColumn dc in dt.Columns)
                {
                    setDelegateString = CreateStringDelegate(model, dc.ColumnName);
                    setDelegateString(dr[dc.ColumnName].ToString());
                }
                lst.Add(model);
            }

            return lst;
        }

        private static SetString CreateStringDelegate(object obj, string PropertyName)
        {
            MethodInfo mi = obj.GetType().GetProperty(PropertyName).GetSetMethod();
            Type type = typeof(SetString);
            return (SetString)Delegate.CreateDelegate(type, obj, mi);
        }
    }


}
